package com.ruoyi.generator.controller;

import cn.hutool.core.io.IoUtil;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.generator.common.query.Query;
import com.ruoyi.generator.domain.ProjectEntity;
import com.ruoyi.generator.service.ProjectService;
import jakarta.servlet.http.HttpServletResponse;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 项目名变更
 */
@RestController
@RequestMapping("gen/project")
@AllArgsConstructor
public class ProjectController extends BaseController {
    private final ProjectService projectService;

    @GetMapping("page")
    public TableDataInfo page(Query query) {
        return getDataTable(projectService.page(query));
    }

    @GetMapping("list")
    public R<List<ProjectEntity>> list(Query query) {
        return R.ok(projectService.list());
    }

    @GetMapping("{id}")
    public R<ProjectEntity> get(@PathVariable("id") Long id) {
        ProjectEntity entity = projectService.getById(id);
        return R.ok(entity);
    }

    @PostMapping
    public R<String> save(@RequestBody ProjectEntity entity) {
        projectService.save(entity);
        return R.ok();
    }

    @PutMapping
    public R<String> update(@RequestBody ProjectEntity entity) {
        projectService.updateById(entity);
        return R.ok();
    }

    @DeleteMapping
    public R<String> delete(@RequestBody List<Long> idList) {
        projectService.removeByIds(idList);
        return R.ok();
    }

    /**
     * 源码下载
     */
    @GetMapping("download/{id}")
    public void download(@PathVariable("id") Long id, HttpServletResponse response) throws Exception {
        // 项目信息
        ProjectEntity project = projectService.getById(id);

        byte[] data = projectService.download(project);

        response.reset();
        response.setHeader("Content-Disposition", "attachment; filename=\"" + project.getModifyProjectName() + ".zip\"");
        response.addHeader("Content-Length", "" + data.length);
        response.setContentType("application/octet-stream; charset=UTF-8");

        IoUtil.write(response.getOutputStream(), false, data);
    }
}